<template>
  <div class="game-container">
    <div class="status">
      得分: {{ score }} | 长度: {{ snake.length }} | 剩余生命: ❤️{{ lives }}
    </div>

    <div class="game-board" :style="boardStyle">
      <div
        v-for="(segment, index) in snake"
        :key="index"
        class="snake-segment"
        :style="getSegmentStyle(segment)"
      ></div>
      <div
        v-for="(foodItem, index) in food"
        :key="`food-${index}`"
        class="food"
        :style="getFoodStyle(foodItem)"
        v-html="foodItem.icon"
      ></div>
    </div>

    <div class="controls">
      <button @click="startGame">新游戏</button>
      <div class="arrows">
        <button @click="changeDirection('up')">↑</button>
        <button @click="changeDirection('left')">←</button>
        <button @click="changeDirection('right')">→</button>
        <button @click="changeDirection('down')">↓</button>
      </div>
      <div>
        <label>难度：</label>
        <select v-model="difficulty">
          <option value="easy">简单</option>
          <option value="medium">中等</option>
          <option value="hard">困难</option>
        </select>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted, onBeforeUnmount } from 'vue'

export default {
  setup() {
    const gridSize = ref(20)
    const snake = reactive([{ x: 5, y: 5 }])
    const direction = ref('right')
    const score = ref(0)
    const lives = ref(3)
    const gameLoop = ref(null)
    const difficulty = ref('medium') // 新增难度选择

    const boardStyle = computed(() => ({
      width: `${gridSize.value * 30}px`,
      height: `${gridSize.value * 30}px`,
      border: '2px solid #333',
      position: 'relative',
      margin: '20px auto'
    }))

    const food = reactive([
      { type: 'normal', icon: '🍎', x: 10, y: 10, score: 10 },
      { type: 'speedUp', icon: '🚀', x: 15, y: 15, score: 0, duration: 2, color: 'red' },
      { type: 'speedDown', icon: '🛑', x: 12, y: 12, score: 0, duration: 2, color: 'blue' },
      { type: 'life', icon: '❤️', x: 8, y: 8, score: 0, color: 'pink' }
    ])

    const getFoodStyle = (foodItem) => ({
      left: `${foodItem.x * 30}px`,
      top: `${foodItem.y * 30}px`,
      color: foodItem.color || 'inherit',
      fontSize: '24px',
      position: 'absolute',
      transition: 'all 0.3s'
    })

    const getSegmentStyle = (segment) => ({
      left: `${segment.x * 30}px`,
      top: `${segment.y * 30}px`,
      background: `hsl(${score.value * 5}, 70%, 50%)`,
      width: '28px',
      height: '28px',
      position: 'absolute',
      transition: 'all 0.1s'
    })

    const spawnFood = (foodItem) => {
      do {
        foodItem.x = Math.floor(Math.random() * gridSize.value)
        foodItem.y = Math.floor(Math.random() * gridSize.value)
      } while (snake.some(seg => seg.x === foodItem.x && seg.y === foodItem.y) ||
               food.some(otherFood => otherFood !== foodItem && otherFood.x === foodItem.x && otherFood.y === foodItem.y))
    }

    const checkCollision = (pos) => {
      return (
        pos.x < 0 || 
        pos.x >= gridSize.value || 
        pos.y < 0 || 
        pos.y >= gridSize.value ||
        snake.some(seg => seg.x === pos.x && seg.y === pos.y)
      )
    }

    const move = () => {
      const head = { ...snake[0] }
      switch(direction.value) {
        case 'up': head.y--; break
        case 'down': head.y++; break
        case 'left': head.x--; break
        case 'right': head.x++; break
      }

      if (checkCollision(head)) {
        lives.value--
        if (lives.value <= 0) {
          alert(`游戏结束！最终得分: ${score.value}`)
          startGame()
        }
        return
      }

      const foodItem = food.find(f => f.x === head.x && f.y === head.y)
      if (foodItem) {
        score.value += foodItem.score
        if (foodItem.type === 'speedUp') {
          clearInterval(gameLoop.value)
          gameLoop.value = setInterval(move, 100)
          setTimeout(() => {
            clearInterval(gameLoop.value)
            gameLoop.value = setInterval(move, getMoveInterval())
          }, foodItem.duration * 1000)
        } else if (foodItem.type === 'speedDown') {
          clearInterval(gameLoop.value)
          gameLoop.value = setInterval(move, 500)
          setTimeout(() => {
            clearInterval(gameLoop.value)
            gameLoop.value = setInterval(move, getMoveInterval())
          }, foodItem.duration * 1000)
        } else if (foodItem.type === 'life') {
          lives.value++
        }
        spawnFood(foodItem) // 只重新生成被吃掉的食物
      }

      // 只有吃到普通食物时才增加蛇的长度
      if (foodItem && foodItem.type === 'normal') {
        snake.unshift(head)
      } else {
        snake.pop()
        snake.unshift(head)
      }
    }

    const startGame = () => {
      clearInterval(gameLoop.value)
      snake.splice(0, snake.length, { x: 5, y: 5 })
      direction.value = 'right'
      score.value = 0
      lives.value = 3
      food.forEach(spawnFood) // 初始化时生成所有食物
      gameLoop.value = setInterval(move, getMoveInterval())
    }

    const changeDirection = (newDir) => {
      const opposite = {
        up: 'down', down: 'up',
        left: 'right', right: 'left'
      }
      if (newDir !== opposite[direction.value]) {
        direction.value = newDir
      }
    }

    const getMoveInterval = () => {
      switch(difficulty.value) {
        case 'easy': return 300
        case 'medium': return 200
        case 'hard': return 100
        default: return 200
      }
    }

    onMounted(() => {
      startGame()
      window.addEventListener('keydown', (e) => {
        const dirMap = {
          ArrowUp: 'up',
          ArrowDown: 'down',
          ArrowLeft: 'left',
          ArrowRight: 'right'
        }
        if (dirMap[e.key]) changeDirection(dirMap[e.key])
      })
    })

    onBeforeUnmount(() => {
      clearInterval(gameLoop.value)
    })

    return {
      snake,
      score,
      lives,
      food,
      boardStyle,
      getFoodStyle,
      getSegmentStyle,
      startGame,
      changeDirection,
      difficulty
    }
  }
}
</script>

<style scoped>
.game-container {
  font-family: Arial, sans-serif;
  text-align: center;
}

.status {
  margin-bottom: 20px;
  font-size: 1.2em;
}

.controls {
  margin-top: 20px;
}

button {
  padding: 10px 15px;
  margin: 0 5px;
  font-size: 1em;
  cursor: pointer;
}

.food {
  position: absolute;
  font-size: 24px;
  transition: all 0.3s;
}

.snake-segment {
  transition: all 0.1s;
}
</style>